package com.yaoandw.storage;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

/**
 * java 版本的berkeley db只支持b-tree
 * c版本的支持Btree、Hash、Heap、Queue、Recno
 * 
 * @author yaowei
 *
 */
public abstract class AbstractFrontier {
	private Environment env;
	private static final String CLASS_CATALOG = "java_class_catalog";
	protected StoredClassCatalog javaCatalog;
	protected Database catalogdatabase;
	protected Database database;

	public AbstractFrontier(String homeDirectory) throws DatabaseException,
			FileNotFoundException {
		// 打开env
		System.out.println("Opening environment in: " + homeDirectory);
		EnvironmentConfig envConfig = new EnvironmentConfig();
		envConfig.setTransactional(true);
		envConfig.setAllowCreate(true);
		File homeEvn = new File(homeDirectory);
		if(!homeEvn.exists())
			homeEvn.mkdirs();
		env = new Environment(homeEvn, envConfig);
		// 设置DatabaseConfig
		DatabaseConfig dbConfig = new DatabaseConfig();
		dbConfig.setTransactional(true);
		dbConfig.setAllowCreate(true);
		// 打开
		catalogdatabase = env.openDatabase(null, CLASS_CATALOG, dbConfig);
		javaCatalog = new StoredClassCatalog(catalogdatabase);
		// 设置DatabaseConfig
		DatabaseConfig dbConfig0 = new DatabaseConfig();
		dbConfig0.setTransactional(true);
		dbConfig0.setAllowCreate(true);
		// 打开
		database = env.openDatabase(null, "URL", dbConfig);
	}

	// 关闭数据库，关闭环境
	public void close() throws DatabaseException {
		database.close();
		javaCatalog.close();
		env.close();
	}

	public Environment getEnv() {
		return env;
	}
	
	protected abstract List<SimpleCrawlUrl> list();

	// put方法
	protected abstract SimpleCrawlUrl put(String key, SimpleCrawlUrl value);

	// get方法
	protected abstract SimpleCrawlUrl get(String key);

	// delete方法
	protected abstract SimpleCrawlUrl delete(String key);
}
